package com.tvunetworks.device.extra.controller;

import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.device.extra.annotation.Logined;
import com.tvunetworks.device.extra.model.param.AddExtToUserParam;
import com.tvunetworks.device.extra.model.param.UpdateExtParam;
import com.tvunetworks.device.extra.service.ExtService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author Etan Yang
 * @create: 2021/11/22 13:40
 */

@RestController
@RequestMapping("/ext")
public class ExtController {
    @Autowired
    private ExtService extService;

    /**
     * add Ext to user,if there is no user in CC service, create a user and the user role defaults to 'user'
     *
     * @param loginUser loginUser
     * @param param addExtToUserParam
     * @return sourceId
     */
    @PostMapping("addExtToUser")
    public Result addExtToUser(@Logined LoginUser loginUser, @Validated @RequestBody AddExtToUserParam param) {
        String userId = StringUtils.isNotEmpty(param.getUserId()) ? param.getUserId() : loginUser.getId();
        param.setUserId(userId);
        String sourceId = extService.addExtToUser(param.getUserId(), param.getSourceName(), param.getSourceType(), param.getUrl(), param.getRid());
        return ResultUtil.success(sourceId);
    }

    /**
     * update ext name or url
     *
     * @param param updateExtParam
     * @return result
     */
    @PostMapping("updateExt")
    public Result updateExt(@Validated@RequestBody UpdateExtParam param) {
        return extService.updateExt(param);
    }

    /**
     * delete ext
     * @param loginUser 登录用户
     * @param sourceId ext sourceId
     * @return result
     */
    @PostMapping("deleteExt")
    public Result deleteExt(@Logined LoginUser loginUser, @RequestParam("sourceId") String sourceId) {
        return extService.deleteExt(sourceId, loginUser.getId());
    }
}
